package cn.weekdragon.gscore.adapter.route;

import cn.hutool.core.util.StrUtil;
import java.util.*;

public class RouteManager {

    private final static List<Route> ALL_ROUTES = new ArrayList<>();
    private final static Map<String,List<Route>> BOT_SERVICE_MAP = new HashMap<>();

    private final static Map<String,List<Route>> SERVICE_BOT_MAP = new HashMap<>();


    public static void addRoute(Route route){
        ALL_ROUTES.add(route);
    }


    public static List<Route> getServices(String botName) {
        List<Route> routes = BOT_SERVICE_MAP.get(botName);
        if (Objects.isNull(routes)) {
            synchronized (BOT_SERVICE_MAP) {
                routes = BOT_SERVICE_MAP.get(botName);
                if (Objects.isNull(routes)) {
                    routes = new ArrayList<>();
                    BOT_SERVICE_MAP.put(botName, routes);
                    for (Route route : ALL_ROUTES) {
                        String bot = route.getBot();
                        if (StrUtil.isEmpty(bot) || botName.equals(bot)) {
                            routes.add(route);
                        }
                    }
                }
            }
        }
        return routes;
    }

    public static List<Route> getBots(String serviceName) {
        List<Route> routes = SERVICE_BOT_MAP.get(serviceName);
        if(Objects.isNull(routes)){
            synchronized (SERVICE_BOT_MAP) {
                routes = SERVICE_BOT_MAP.get(serviceName);
                if(Objects.isNull(routes)){
                    routes = new ArrayList<>();
                    SERVICE_BOT_MAP.put(serviceName,routes);
                    for (Route route : ALL_ROUTES) {
                        String service = route.getService();
                        if(StrUtil.isEmpty(service) || serviceName.equals(service)){
                            routes.add(route);
                        }
                    }
                }
            }
        }
        return routes;
    }
}
